package com.example.android.commitcontent.ime.activities;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.example.android.commitcontent.ime.BuildConfig;
import com.example.android.commitcontent.ime.R;
import com.example.android.commitcontent.ime.beans.HanZiCharacter;
import com.example.android.commitcontent.ime.beans.HanZiWord;
import com.example.android.commitcontent.ime.cores.base.BaseActivity;
import com.example.android.commitcontent.ime.cores.utils.JSONHelper;
import com.example.android.commitcontent.ime.cores.utils.LogHelper;
import com.example.android.commitcontent.ime.cores.utils.SPHelper;
import com.example.android.commitcontent.ime.cores.utils.ToastHelper;
import com.example.android.commitcontent.ime.cores.widgets.GeneralDialog;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;
import com.example.android.commitcontent.ime.database.managers.HanZiWordDictManager;
import com.example.android.commitcontent.ime.dict.HanZiDictHelper;
import com.example.android.commitcontent.ime.setting.SettingAdapter;
import com.example.android.commitcontent.ime.setting.SettingBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.pluss.baselibrary.http.HttpRequest;
import cn.pluss.baselibrary.http.callback.SimpleHttpCallBack;
import cn.pluss.baselibrary.http.exception.ApiException;

public class SettingActivity extends BaseActivity {

    @BindView(R.id.rv_list)
    RecyclerView recyclerView;
    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    private static final String KEY_UPDATE_TIME = "update_time";

    private List<SettingBean> mSettingBeanList = new ArrayList<>();

    public static void start(Context context) {
        context.startActivity(new Intent(context, SettingActivity.class));
    }

    @Override
    protected int setLayoutRes() {
        return R.layout.activity_setting;
    }

    @Override
    protected boolean isNeedSlideBack() {
        return true;
    }

    private SettingAdapter adapter;

    @Override
    protected void initView() {
        hideTitleMoreButton();
        setTitleBarText("设置");


        mSettingBeanList.add(new SettingBean("常规设置"));
        mSettingBeanList.add(new SettingBean("同步最新词库", ""));
//        mSettingBeanList.add(new SettingBean("隐藏App桌面图标", "启用后应用图标将不会在桌面显示，隐藏后可以从设置-语言和输入法中启用桌面显示"));
        mSettingBeanList.add(new SettingBean("软件信息"));
        mSettingBeanList.add(new SettingBean("软件版本", String.format("Ver %s", BuildConfig.VERSION_NAME)));

        adapter = new SettingAdapter(this, mSettingBeanList);
        adapter.setOnItemClickListener(new SettingAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    case 0:
                        updateWordsDictOrDisplay(true);
                        break;
                    case 1:
//                        hideAppDesktopIcon();
                        break;
                }
            }
        });
        adapter.setOnItemLongClickListener(new SettingAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClick(int position) {
                switch (position) {
                    case 0:
                        //todo 将服务器获取的汉字添加到本地库，然后加载到内存
//                        ArrayList<HanZiCharacter> hanZiCharacterList = new ArrayList<>();
//                        hanZiCharacterList.add(new HanZiCharacter("我", "w", "o", "wo", 7, "3"));
//                        hanZiCharacterList.add(new HanZiCharacter("累e", "w", "o", "wo", 7, "3"));
//                        HanZiStatisticsDataBaseHelper.intance(SettingActivity.this).saveHanZi(hanZiCharacterList);
//                        HanZiDictHelper.loadDatabaseHanZiToMemory(SettingActivity.this);
                        break;
                    case 1:
                        HanZiStatisticsManageActivity.start(SettingActivity.this);
                        break;
                }
            }
        });
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        updateWordsDictOrDisplay(false);
    }

    private void hideAppDesktopIcon() {
        new GeneralDialog.Builder(SettingActivity.this)
                .setTitleText("提示")
                .setContentText("确认将应用图标从桌面隐藏？此设置可能需要一会才能生效，部分桌面需要重启后生效。")
                .setPositiveButton("确认隐藏", new GeneralDialog.OnButtonClickListener() {
                    @Override
                    public void onClick(Dialog dialog) {
                        dialog.dismiss();
//                                getPackageManager().setComponentEnabledSetting(MainActivity.COMPONENT_NAME, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                                        PackageManager.DONT_KILL_APP);
                    }
                })
                .setNegativeButton("取消", new GeneralDialog.OnButtonClickListener() {
                    @Override
                    public void onClick(Dialog dialog) {
                        dialog.dismiss();
//                                getPackageManager().setComponentEnabledSetting(MainActivity.COMPONENT_NAME, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
//                                        PackageManager.DONT_KILL_APP);
                    }
                })
                .build().show();
    }

    /**
     * 更新词库
     */
    public void updateWordDict() {
        HttpRequest.post("queryLexicon")
                .bindLifecycle(this)
                .executeArray(HanZiWord.class, new SimpleHttpCallBack<HanZiWord>() {
                    @Override
                    public void onStart() {
                        showLoadingDialog("词库同步中", "从服务器获取信息");
                    }

                    @Override
                    public void onSuccess(ArrayList<HanZiWord> list) {
                        showLoadingDialog("词库同步中", "数据同步中，请勿退出应用");
                        HanZiWordDictManager.instance(SettingActivity.this).updateWordsDict(list, new HanZiWordDictManager.OnWordsUpdateSuccessListener() {
                            @Override
                            public void onWordsUpdateSuccess() {
                                ToastHelper.show(SettingActivity.this, "本地词库更新完成");
                                dismissLoadingDialog();
                                SPHelper.put(SettingActivity.this, KEY_UPDATE_TIME, System.currentTimeMillis());
                                updateWordsDictOrDisplay(false);
                            }
                        });
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissLoadingDialog();
                        ToastHelper.show(SettingActivity.this, e.getMessage());
                    }

                    @Override
                    public void onCompleted() {
                    }
                });
    }

    private void updateWordsDictOrDisplay(boolean isUpdateMode) {
        if (isCanUpdate()) {
            mSettingBeanList.get(1).setDesc("从服务器获取最新词库数据");
            if (isUpdateMode)
                updateWordDict();
        } else {
            mSettingBeanList.get(1).setDesc(String.format("上次同步时间 %s", mSimpleDateFormat.format(new Date(SPHelper.get(this, KEY_UPDATE_TIME, 0L)))));
            if (isUpdateMode)
                ToastHelper.show(SettingActivity.this, "刚才已更新，无需频繁更新");
        }
        adapter.notifyDataSetChanged();
    }

    private boolean isCanUpdate() {
        long lastUpdateTime = SPHelper.get(SettingActivity.this, KEY_UPDATE_TIME, 0L);
        long time = (System.currentTimeMillis() - lastUpdateTime) / 1000 / 60;
        return time >= 5;
    }

    @Override
    protected void initData() {

    }

}
